<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="70px">

      <el-form-item label="分类区域" prop="areaId">
        <el-tree-select v-model="queryParams.areaId" :data="areaOptions"
          :props="{ value: 'id', label: 'name', children: 'childs' }" value-key="id" placeholder="请选择区域/楼宇/单元"
          check-strictly style="width: 240px" clearable @keyup.enter="handleQuery" @change="handleAreaQueryChange" />
      </el-form-item>
      <el-form-item label="房号" prop="roomCode">
        <el-input v-model="queryParams.roomCode" placeholder="请输入房号" style="width: 200px" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="使用状态" prop="useStatus">
        <el-select v-model="queryParams.useStatus" placeholder="请选择使用状态" clearable style="width: 200px">
          <el-option v-for="item in useStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="销售状态" prop="saleStatus">
        <el-select v-model="queryParams.saleStatus" placeholder="请选择销售状态" clearable style="width: 200px">
          <el-option v-for="item in saleStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="收楼状态" prop="collectStatus">
        <el-select v-model="queryParams.collectStatus" placeholder="请选择收楼状态" clearable style="width: 200px">
          <el-option v-for="item in collectStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="入住状态" prop="liveStatus">
        <el-select v-model="queryParams.liveStatus" placeholder="请选择入住状态" clearable style="width: 200px">
          <el-option v-for="item in liveStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="装修状态" prop="decorationStatus">
        <el-select v-model="queryParams.decorationStatus" placeholder="请选择装修状态" clearable style="width: 200px">
          <el-option v-for="item in decorationStatusOptions" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="createDate">
        <el-date-picker v-model="queryParams.createDate" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>

      <!-- <el-form-item label="关键词" prop="keyword">
            <el-input v-model="queryParams.keyword"  style="width: 200px"  placeholder="请输入地址 / 房号" clearable  />
          </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>

      <!-- <el-form-item label="房屋标签"  >
            <el-input   style="width: 200px" v-model="queryParams.tags" placeholder="请选择房屋标签" clearable />
          </el-form-item> -->

      <!-- <el-row :gutter="16">
        <el-col :span="6">
          <el-form-item label="销售状态" prop="saleStatus" style="width: 100%;">
            <el-select v-model="queryParams.saleStatus" placeholder="请选择销售状态" clearable style="width: 100%">
              <el-option v-for="item in saleStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="销售时间" prop="saleDate" style="width: 100%;">
            <el-date-picker v-model="queryParams.saleDate" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收楼状态" prop="collectStatus" style="width: 100%;">
            <el-select v-model="queryParams.collectStatus" placeholder="请选择收楼状态" clearable>
              <el-option v-for="item in collectStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收楼时间" prop="collectDate" style="width: 100%;">
            <el-date-picker v-model="queryParams.collectDate" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row> -->
      <!-- <el-row :gutter="16">
        <el-col :span="6">
          <el-form-item label="入住状态" prop="liveStatus" style="width: 100%;">
            <el-select v-model="queryParams.liveStatus" placeholder="请选择入住状态" clearable>
              <el-option v-for="item in liveStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入住时间" prop="liveDate" style="width: 100%;">
            <el-date-picker v-model="queryParams.liveDate" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="装修状态" prop="decorationStatus" style="width: 100%;">
            <el-select v-model="queryParams.decorationStatus" placeholder="请选择装修状态" clearable>
              <el-option v-for="item in decorationStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="装修时间" prop="decorationDate" style="width: 100%;">
            <el-date-picker v-model="queryParams.decorationDate" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row> -->




    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
     
      <el-col :span="1.5">
        <el-button icon="Download" @click="handleExport">导出</el-button>
      </el-col> -->

      
       <!-- <el-col :span="1.5">
            <el-button
               type="primary"
               plain
               icon="Plus"
               @click="handleAdd"
               v-hasPermi="['system:post:add']"
            >新增</el-button>
            
         </el-col> -->
        
          <!-- <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Upload"
            @click="importDialogVisible = true"
          >导入</el-button>
        </el-col> -->
     
      
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleEdit()"
         >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
         >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Upload" @click="importDialogVisible = true">导入</el-button>
      </el-col>
      <el-col :span="1.5">
          <el-button icon="Download" @click="handleExportTemplate">下载模板</el-button>
        </el-col>
       



    </el-row>

    <!-- 表格 -->
    <el-table border v-loading="loading" :data="roomList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
    
      <el-table-column label="区域" prop="areaId" min-width="100">
        <template #default="scope">
          {{ scope.row.areaName }}
        </template>
      </el-table-column>

      <el-table-column label="楼宇" prop="areaId" min-width="100">
        <template #default="scope">
          {{ scope.row.buildName }}
        </template>
      </el-table-column>
      <el-table-column label="单元" prop="areaId" min-width="100">
        <template #default="scope">
          {{ scope.row.unitName }}
        </template>
      </el-table-column>

      <el-table-column label="楼层" prop="floor" min-width="60">
        <template #default="scope">
          {{ scope.row.pmsHouse.floor }}
        </template>
      </el-table-column>
      <el-table-column label="房号" prop="roomCode" min-width="80">
        <template #default="scope">
          {{ scope.row.pmsHouse.roomCode }}
        </template>
      </el-table-column>
      <el-table-column label="面积" prop="houseSize" min-width="80">
        <template #default="scope">
          {{ scope.row.pmsHouse.houseSize }}
        </template>
      </el-table-column>
      <el-table-column label="产权人" prop="saleStatus" min-width="200">
        <template #default="scope">
          <el-popover placement="top-start" :width="300" trigger="hover"
            v-if="scope.row.pmsHouseBindUsers && scope.row.pmsHouseBindUsers.length > 0">
            <template #default>
              <div>
                <div v-for="(user, index) in scope.row.pmsHouseBindUsers" :key="index" style="margin-bottom: 8px;">
                  <span>{{ user.name }}</span>
                  <span style="color: #666; margin-left: 8px;">({{ user.mobile }})</span>
                </div>
              </div>
            </template>
            <template #reference>
              <span
                style="cursor: pointer; color: #409eff; display: flex; align-items: center; justify-content: space-between;">
                <span>{{ scope.row.pmsHouseBindUsers.length > 0 ? scope.row.pmsHouseBindUsers[0].name + '(' +
                  scope.row.pmsHouseBindUsers[0].mobile + ')' + (scope.row.pmsHouseBindUsers.length > 1 ? ' 等' +
                    scope.row.pmsHouseBindUsers.length + '人' : '') : '' }}</span>
                <el-icon style="margin-left: 4px; font-size: 12px;">
                  <ArrowDown />
                </el-icon>
              </span>
            </template>
          </el-popover>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="套内面积" prop="houseInnerSize" min-width="80">
        <template #default="scope">
          {{ scope.row.pmsHouse.houseInnerSize }}
        </template>
      </el-table-column>
      <el-table-column label="使用状态" prop="useStatus" min-width="90">
        <template #default="scope">
          {{useStatusOptions.find(item => item.value === scope.row.pmsHouse.useStatus)?.label}}
        </template>
      </el-table-column>
      <el-table-column label="标签" prop="tags" min-width="100">
        <template #default="scope">
          {{ scope.row.pmsHouse.tags }}
        </template>
      </el-table-column>
      <el-table-column label="地址" prop="address" min-width="150">
        <template #default="scope">
          {{ scope.row.pmsHouse.address }}
        </template>
      </el-table-column>
      <el-table-column label="销售状态" prop="saleStatus" min-width="90">
        <template #default="scope">
          {{saleStatusOptions.find(item => item.value === scope.row.pmsHouse.saleStatus)?.label}}
        </template>
      </el-table-column>
      <el-table-column label="销售时间" prop="saleDate" min-width="140">
        <template #default="scope">
          {{ scope.row.pmsHouse.saleDate }}
        </template>
      </el-table-column>
      <el-table-column label="收楼状态" prop="collectStatus" min-width="90">
        <template #default="scope">
          {{collectStatusOptions.find(item => item.value === scope.row.pmsHouse.collectStatus)?.label}}
        </template>
      </el-table-column>
      <el-table-column label="应收楼时间" prop="contractCollectDate" min-width="140">
        <template #default="scope">
          {{ scope.row.pmsHouse.contractCollectDate }}
        </template>
      </el-table-column>
      <el-table-column label="收楼时间" prop="collectDate" min-width="140">
        <template #default="scope">
          {{ scope.row.pmsHouse.collectDate }}
        </template>
      </el-table-column>
      <el-table-column label="入住状态" prop="liveStatus" min-width="90">
        <template #default="scope">
          {{liveStatusOptions.find(item => item.value === scope.row.pmsHouse.liveStatus)?.label}}
        </template>
      </el-table-column>
      <el-table-column label="入住时间" prop="liveDate" min-width="140">
        <template #default="scope">
          {{ scope.row.pmsHouse.liveDate }}
        </template>
      </el-table-column>
      <el-table-column label="装修状态" prop="decorationStatus" min-width="90">
        <template #default="scope">
          {{ scope.row.pmsHouse.decorationStatusDesc }}

        </template>
      </el-table-column>
      <el-table-column label="装修时间" prop="decorationDate" min-width="140">
        <template #default="scope">
          {{ scope.row.pmsHouse.decorationDate }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createDate" min-width="140">
        <template #default="scope">
          {{ scope.row.pmsHouse.createDate }}
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" min-width="60">
        <template #default="scope">
          {{ scope.row.pmsHouse.sort }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <AmpMap />

    <!-- 新增抽屉 -->
    <el-drawer v-model="drawerVisible" @close="handleClose" :title="isEdit ? '编辑房屋' : '新增房屋'" size="50%"
      :with-header="true" :close-on-click-modal="false">
      <el-card shadow="never" style="margin-bottom: 16px;">
        <template #header>
          <span>基础信息</span>
        </template>
        <el-form ref="drawerFormRef" :model="drawerForm" :rules="drawerRules" label-width="100px">
          <el-row :gutter="20">
            <!-- <el-col :span="12">
              <el-form-item label="小区" prop="communityId" required>
                <el-select v-model="drawerForm.communityId" placeholder="请选择小区" style="width: 100%">
                  <el-option v-for="item in communityOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="分类区域" required>
                <el-tree-select default-expand-all v-model="selectedAreaId" :data="areaOptions"
                  :props="{ value: 'id', label: 'name', children: 'childs' }" value-key="id" placeholder="请选择分类区域"
                  check-strictly style="width: 100%" @change="handleAreaChange" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房号" prop="roomCode" required>
                <el-input v-model="drawerForm.roomCode" placeholder="请输入房号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="楼层" prop="floor" required>
                <el-input v-model="drawerForm.floor" placeholder="请输入楼层" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户行" >
                <el-input v-model="drawerForm.bankName" placeholder="请输入开户行" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行卡号" >
                <el-input v-model="drawerForm.bankCard" placeholder="请输入银行卡号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="持卡人"  >
                <el-input v-model="drawerForm.bankCardHolder" placeholder="请输入持卡人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地址" >
                <el-input v-model="drawerForm.address" placeholder="请输入地址">
                  <template #append>
                    <el-button icon="Location" @click="mapDialogVisible = true" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="面积" >
                <el-input-number v-model="drawerForm.houseSize" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="套内面积" >
                <el-input-number v-model="drawerForm.houseInnerSize" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序"  >
                <el-input-number v-model="drawerForm.sort" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建时间"  >
                <el-date-picker v-model="drawerForm.createDate" type="date" placeholder="选择日期" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="销售时间"  >
                <el-date-picker v-model="drawerForm.saleDate" type="date" placeholder="选择日期" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="应收楼时间" >
                <el-date-picker v-model="drawerForm.contractCollectDate" type="date" placeholder="选择日期"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收楼时间" >
                <el-date-picker v-model="drawerForm.collectDate" type="date" placeholder="选择日期" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="装修时间"  >
                <el-date-picker v-model="drawerForm.decorationDate" type="date" placeholder="选择日期"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入住时间" >
                <el-date-picker v-model="drawerForm.liveDate" type="date" placeholder="选择日期" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card shadow="never" style="margin-bottom: 16px;">
        <template #header>
          <span>房屋状态</span>
        </template>
        <el-form :model="drawerForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="销售状态" prop="saleStatus" required>
                <el-radio-group v-model="drawerForm.saleStatus">
                  <!-- <el-radio :label="1">未销售</el-radio>
                  <el-radio :label="2">已销售</el-radio> -->
                  <el-radio v-for="item in saleStatusOptions" :key="item.value" :label="item.value">{{ item.label
                  }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="收楼状态" prop="collectStatus">
                <el-radio-group v-model="drawerForm.collectStatus">
                  <!-- <el-radio :label="1">未收楼</el-radio>
                    <el-radio :label="2">已收楼</el-radio> -->
                  <el-radio v-for="item in collectStatusOptions" :key="item.value" :label="item.value">{{ item.label
                  }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="装修状态" prop="decorationStatus">
                <el-radio-group v-model="drawerForm.decorationStatus">
                  <!-- <el-radio :label="1">未装修</el-radio>
                  <el-radio :label="2">已装修</el-radio> -->
                  <el-radio v-for="item in decorationStatusOptions" :key="item.value" :label="item.value">{{ item.label
                  }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="入住状态" prop="liveStatus">
                <el-radio-group v-model="drawerForm.liveStatus">
                  <!-- <el-radio :label="1">未入住</el-radio>
                  <el-radio :label="2">已入住</el-radio> -->
                  <el-radio v-for="item in liveStatusOptions" :key="item.value" :label="item.value">{{ item.label
                  }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="使用状态" prop="useStatus">
                <el-radio-group v-model="drawerForm.useStatus">
                  <!-- <el-radio :label="1">自住</el-radio>
                  <el-radio :label="2">闲置</el-radio>
                  <el-radio :label="3">出租</el-radio>
                  <el-radio :label="4">其他</el-radio> -->
                  <el-radio v-for="item in useStatusOptions" :key="item.value" :label="item.value">{{ item.label
                  }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card shadow="never" style="margin-bottom: 16px;">
        <template #header>
          <span>银行代扣</span>
        </template>
        <el-form :model="drawerForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="银行代扣" prop="bankStatus">
                <el-radio-group v-model="drawerForm.bankStatus">
                  <el-radio :label="2">关闭</el-radio>
                  <el-radio :label="1">开启</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <div style="text-align: right;">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleDrawerSave">保存</el-button>
      </div>
    </el-drawer>
    <AmpMap v-model="mapDialogVisible" @change="handleMapChange" />
    <!-- 导入弹窗 -->
    <el-dialog :align-center="true" v-model="importDialogVisible" title="导入房屋" width="700px"
      :close-on-click-modal="false">
      <el-upload ref="uploadRef" class="upload-demo" :action="uploadFileUrl" :show-file-list="true" :headers="headers" :limit="1"
        :on-success="handleImportSuccess" :on-error="handleImportError" :on-exceed="handleExceed" 
        drag accept=".xlsx,.xls" :auto-upload="true">
        <div class="upload-demo-btn">
          <el-icon size="50" class="el-icon--upload"><upload-filled /></el-icon>
          <div class="upload-demo-btn-text">导入Excel</div>
          <div class="upload-demo-btn-text-desc">
            将文件拖拽到此处或<span> 点击上传</span>，只支持 .xlsx/.xls 文件</div>
        </div>
        <template #tip>
          <div class="el-upload__tip">只支持上传1个Excel文件(.xlsx/.xls)，选择后自动上传</div>
        </template>
      </el-upload>
      <template #footer>

      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import AmpMap from '@/components/AmpMap/index.vue'
import { ref, reactive, toRefs, onMounted } from 'vue'
import { listHouse, addHouse, updateHouse, delHouse, listCommunity } from '@/api/house/room'
import { listArea } from '@/api/house/area'
import dayjs from 'dayjs'
import { getToken } from "@/utils/auth"
const { proxy } = getCurrentInstance()

// 在顶部添加公共常量
const AREA_ID_KEYS = ['areaIdZero', 'areaIdOne', 'areaIdTwo', 'areaIdThree', 'areaIdFour'];

// 小区选项
const communityOptions = ref([])

// 区域数据处理函数 - 与区域管理保持一致
function normalizeAreaTree(data, parentLevel = 0) {
  // 递归处理每一层
  return data.map(area => {
    const level = parentLevel + 1;
    // 一级区域
    const areaNode = {
      ...area,
      id: area.areaId, // 区域使用 areaId
      level,
      childs: []
    };
    // 二级楼宇
    if (Array.isArray(area.pmsBuilds)) {
      areaNode.childs = area.pmsBuilds.map(build => {
        const buildNode = {
          ...build,
          id: build.id, // 楼宇使用 id
          level: level + 1,
          childs: []
        };
        // 三级单元
        if (Array.isArray(build.units)) {
          buildNode.childs = build.units.map(unit => ({
            ...unit,
            id: unit.id, // 单元使用 id
            level: level + 2,
            areaId: area.areaId, // 添加区域ID
            buildId: build.id, // 添加楼宇ID
            childs: []
          }));
        }
        return buildNode;
      });
    }
    return areaNode;
  });
}


// 房屋状态选项
const saleStatusOptions = [
  { value: 1, label: '未销售' },
  { value: 2, label: '已销售' },
  { value: 99, label: '未知' }
]
const collectStatusOptions = [
  { value: 1, label: '未收楼' },
  { value: 2, label: '已收楼' },
  { value: 99, label: '未知' }
]
const decorationStatusOptions = [
  { value: 1, label: '未装修' },
  { value: 2, label: '已装修' },
  { value: 3, label: '未知' }
]
const liveStatusOptions = [
  { value: 1, label: '未入住' },
  { value: 2, label: '已入住' },
  { value: 99, label: '未知' }
]
const useStatusOptions = [
  { value: 1, label: '自住' },
  { value: 2, label: '闲置' },
  { value: 3, label: '出租' },
  { value: 4, label: '其他' },
  { value: 99, label: '未知' }
]
const bankStatusOptions = [
  { value: 1, label: '开启' },
  { value: 2, label: '关闭' }
]

const loading = ref(false)
const roomList = ref([])
const total = ref(0)
const multiple = ref(true)
const ids = ref([])
const single = ref(true)
const importDialogVisible = ref(false)
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    communityId: '',
    areaId: '',
    buildId: '',   // 楼宇ID
    unitId: '' ,    // 单元ID
    roomCode: '',
    floor: '',
    bankName: '',
    bankCard: '',
    bankCardHolder: '',
    address: '',
    tags: '',
    area: '',
    indoorArea: '',
    saleStatus: '',
    collectStatus: '',
    decorationStatus: '',
    liveStatus: '',
    useStatus: '',
    bankStatus: '',
    createDate: '',
    saleDate: '',
    contractCollectDate: '',
    collectDate: '',
    decorationDate: '',
    liveDate: '',
    sort: ''
  }
})
const { queryParams } = toRefs(data)

// 弹窗相关
const drawerVisible = ref(false)
const drawerFormRef = ref(null)
const isEdit = ref(false)
const mapDialogVisible = ref(false)
const drawerForm = reactive({
  communityId: '',
  areaId: '',
  buildId: '',
  unitId: '',
  selectedLevel: '', // 添加选中级别字段
  roomCode: '',
  floor: '',
  bankName: '',
  bankCard: '',
  bankCardHolder: '',
  address: '',
  lat: '',
  lng: '',
  tags: '',
  area: '',
  indoorArea: '',
  saleStatus: 1,
  collectStatus: 1,
  decorationStatus: 1,
  liveStatus: 1,
  useStatus: 1,
  bankStatus: 1,
  createDate: '',
  saleDate: '',
  contractCollectDate: '',
  collectDate: '',
  decorationDate: '',
  liveDate: '',
  sort: '',
  areaIdZero: "",
  areaIdOne: ""
})
const drawerRules = {
  communityId: [{ required: true, message: '请选择小区', trigger: 'change' }],
  roomCode: [{ required: true, message: '请输入房号', trigger: 'blur' }],
  floor: [{ required: true, message: '请输入楼层', trigger: 'blur' }],
  bankName: [{ required: true, message: '请输入开户行', trigger: 'blur' }],
  bankCard: [{ required: true, message: '请输入银行卡号', trigger: 'blur' }],
  bankCardHolder: [{ required: true, message: '请输入持卡人', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  tags: [{ required: true, message: '请输入标签', trigger: 'blur' }],
  area: [{ required: true, message: '请输入面积', trigger: 'blur' }],
  indoorArea: [{ required: true, message: '请输入套内面积', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  createDate: [{ required: true, message: '请选择创建时间', trigger: 'change' }],
  saleDate: [{ required: true, message: '请选择销售时间', trigger: 'change' }],
  contractCollectDate: [{ required: true, message: '请选择应收楼时间', trigger: 'change' }],
  collectDate: [{ required: true, message: '请选择收楼时间', trigger: 'change' }],
  decorationDate: [{ required: true, message: '请选择装修时间', trigger: 'change' }],
  liveDate: [{ required: true, message: '请选择入住时间', trigger: 'change' }],
  saleStatus: [{ required: true, message: '请选择销售状态', trigger: 'change' }],
  collectStatus: [{ required: true, message: '请选择收楼状态', trigger: 'change' }],
  decorationStatus: [{ required: true, message: '请选择装修状态', trigger: 'change' }],
  liveStatus: [{ required: true, message: '请选择入住状态', trigger: 'change' }],
  useStatus: [{ required: true, message: '请选择使用状态', trigger: 'change' }],
  bankStatus: [{ required: true, message: '请选择银行代扣状态', trigger: 'change' }],
  houseInnerSize: [{ required: true, message: '请输入套内面积', trigger: 'blur' }]
}
const areaOptions = ref([])
const selectedAreaId = ref('')
// function handleAreaChange(value) {
//   console.log("value",value)
//   const path = findPath(areaOptions.value, value);
//   console.log('选中节点路径上的所有areaId:', path);
//   if(path.length > 0){
//     drawerForm.areaIdZero = path[0]
//   }
//   if(path.length > 1){
//     drawerForm.areaIdOne = path[1]
//   }
// }
function handleAreaChange(value) {
  console.log('选中的节点ID:', value);

  // 清空所有层级ID
  AREA_ID_KEYS.forEach(key => {
    drawerForm[key] = '';
  });

  if (value) {
    // 根据选中的节点类型设置对应的字段
    const selectedNode = findNodeById(areaOptions.value, value);
    if (selectedNode) {
      console.log('选中的节点:', selectedNode);

      // 设置选中的级别
      drawerForm.selectedLevel = selectedNode.level;

      if (selectedNode.level === 1) {
        // 区域节点
        drawerForm.areaId = selectedNode.areaId;
        drawerForm.buildId = '';
        drawerForm.unitId = '';
      } else if (selectedNode.level === 2) {
        // 楼宇节点
        drawerForm.areaId = selectedNode.areaId;
        drawerForm.buildId = selectedNode.id;
        drawerForm.unitId = '';
      } else if (selectedNode.level === 3) {
        // 单元节点
        drawerForm.areaId = selectedNode.areaId;
        drawerForm.buildId = selectedNode.buildId;
        drawerForm.unitId = selectedNode.id;
      }
      console.log("drawerForm", drawerForm)
    }
  }
}
function findNodeById(tree, targetId) {
  for (const node of tree) {
    if (node.id === targetId) {
      return node;
    }
    if (node.childs && node.childs.length) {
      const result = findNodeById(node.childs, targetId);
      if (result) return result;
    }
  }
  return null;
}
function handleExportTemplate(){
  window.open("https://ainij.oss-cn-beijing.aliyuncs.com/pms/%E6%88%BF%E5%B1%8B%E7%AE%A1%E7%90%86%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx")
}

function findPath(tree, targetId, path = []) {
  for (const node of tree) {
    // 根据节点类型确定ID字段
    let nodeId;
    if (node.areaId) {
      nodeId = node.areaId; // 区域节点
    } else if (node.id) {
      nodeId = node.id; // 楼宇或单元节点
    } else if (node.buildId) {
      nodeId = node.buildId; // 楼宇节点
    } else if (node.unitId) {
      nodeId = node.unitId; // 单元节点
    } else {
      continue; // 跳过无效节点
    }

    const newPath = [...path, nodeId];
    if (nodeId === targetId) {
      return newPath;
    }
    if (node.childs && node.childs.length) {
      const result = findPath(node.childs, targetId, newPath);
      if (result) return result;
    }
  }
  return null;
}


function getCommunityOptions() {
  listCommunity({}).then(res => {
    communityOptions.value = (res?.rows || []).map(item => ({ value: item.communityId, label: item.name }))
  })
}

function handleClose() {
  drawerVisible.value = false
  drawerFormRef.value.resetFields()
  selectedAreaId.value = ''
}


function getList() {
  loading.value = true
  // 创建查询参数副本
  const params = { ...queryParams.value }
  // 处理日期范围参数
  if (params.createDate && Array.isArray(params.createDate)) {
    params.startCreateDate = params.createDate[0]
    params.endCreateDate = params.createDate[1]
    delete params.createDate
  }
  listHouse(params).then(res => {
    roomList.value = res?.rows || []
    total.value = res?.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

function handleAreaQueryChange(value) {
  console.log('选中的节点ID:', value);

  // 清空所有层级ID
  queryParams.value.areaId = '';
  queryParams.value.buildId = '';
  queryParams.value.unitId = '';

  if (value) {
    // 根据选中的节点类型设置对应的字段
    const selectedNode = findNodeById(areaOptions.value, value);
    if (selectedNode) {
      console.log('选中的节点:', selectedNode);

      if (selectedNode.level === 1) {
        // 区域节点
        queryParams.value.areaId = selectedNode.areaId;
      } else if (selectedNode.level === 2) {
        // 楼宇节点
        queryParams.value.areaId = selectedNode.areaId;
        queryParams.value.buildId = selectedNode.id;
      } else if (selectedNode.level === 3) {
        // 单元节点
        queryParams.value.areaId = selectedNode.areaId;
        queryParams.value.buildId = selectedNode.buildId;
        queryParams.value.unitId = selectedNode.id;
      }
      console.log("queryParams", queryParams.value)
    }
  }
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  Object.keys(queryParams.value).forEach(key => {
    if (Array.isArray(queryParams.value[key])) {
      queryParams.value[key] = []
    } else {
      queryParams.value[key] = ''
    }
  })
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.pmsHouse.houseId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

function handleAdd() {
  isEdit.value = false
  Object.assign(drawerForm, {
    communityId: '',
    areaId: '',
    buildId: '',
    unitId: '',
    selectedLevel: '',
    roomCode: '',
    floor: '',
    bankName: '',
    bankCard: '',
    bankCardHolder: '',
    address: '',
    lat: '',
    lng: '',
    tags: '',
    area: '',
    indoorArea: '',
    saleStatus: 1,
    collectStatus: 1,
    decorationStatus: 1,
    liveStatus: 1,
    useStatus: 1,
    bankStatus: 1,
    createDate: '',
    saleDate: '',
    contractCollectDate: '',
    collectDate: '',
    decorationDate: '',
    liveDate: '',
    sort: ''
  })

  // 初始化所有层级ID
  AREA_ID_KEYS.forEach(key => {
    drawerForm[key] = '';
  });

  // 清空选中状态
  selectedAreaId.value = '';

  drawerVisible.value = true
}
function handleEdit(row) {
  if (!row) {
    let id = ids.value[0]
    row = roomList.value.find(item => item.houseId == id)
  }
  console.log("row",row)
  isEdit.value = true
  Object.assign(drawerForm, row,row.pmsHouse)

  // 根据层级ID设置树形选择器的显示值和级别
  if (drawerForm.unitId) {
    // 如果有单元ID，显示单元，级别为3
    selectedAreaId.value = drawerForm.unitId;
    drawerForm.selectedLevel = 3;
  } else if (drawerForm.buildId) {
    // 如果有楼宇ID，显示楼宇，级别为2
    selectedAreaId.value = drawerForm.buildId;
    drawerForm.selectedLevel = 2;
  } else if (drawerForm.areaId) {
    // 如果有区域ID，显示区域，级别为1
    selectedAreaId.value = drawerForm.areaId;
    drawerForm.selectedLevel = 1;
  }

  console.log('编辑时设置的selectedAreaId:', selectedAreaId.value, '级别:', drawerForm.selectedLevel);

  // 确保所有层级ID都被正确设置
  AREA_ID_KEYS.forEach(key => {
    if (!drawerForm[key]) {
      drawerForm[key] = '';
    }
  });

  drawerVisible.value = true
}
function handleDelete(row) {
  console.log("ids",ids.value,row)
  const delIds = row ? [row.pmsHouse.houseId] : ids.value
  if (!delIds.length) return
  proxy.$modal.confirm('是否确认删除房屋编号为"' + delIds + '"的数据项?').then(function () {
    return Promise.all(delIds.map(id => delHouse(id)))
  }).then(() => {
    proxy.$modal?.success?.('删除成功') || this?.$message?.success('删除成功')
    getList() 
  }).catch(() => { })
}
function handleImport() {
  // 预留导入逻辑
}
function handleExport() {
  proxy.download(
    'pms/house/export',
    { ...queryParams.value },
    `house_${new Date().getTime()}.xlsx`
  )
}
function handleDrawerSave() {
  // 手动验证分类区域是否已选择
  if (!selectedAreaId.value) {
    proxy.$modal.msgError('请选择分类区域')
    return
  }

  drawerFormRef.value.validate(valid => {
    if (valid) {
      const payload = { ...drawerForm }

      // 保留所有层级ID字段，确保完整的层级关系被提交
      // 不对任何ID字段进行删除或清空操作

      // 删除 selectedLevel 字段，不需要传递给后端
      delete payload.selectedLevel

      // 格式化日期字段
      const dateFields = [
        'collectDate',
        'contractCollectDate',
        'createDate',
        'decorationDate',
        'liveDate',
        'saleDate'
      ]
      dateFields.forEach(field => {
        if (payload[field]) {
          payload[field] = dayjs(payload[field]).format('YYYY-MM-DD HH:mm:ss')
        }
      })

      console.log('提交的数据:', payload)


      const req = isEdit.value ? updateHouse(payload) : addHouse(payload)
      req.then(() => {
        proxy.$modal?.success?.('保存成功') || this?.$message?.success('保存成功')
        drawerVisible.value = false
        getList()
        scrollToTop()
      })
    }
  })
}

function scrollToTop() {
  // 获取抽屉容器并滚动到顶部
  const drawerContainer = document.querySelector('.el-drawer__body')
  if (drawerContainer) {
    drawerContainer.scrollTo({
      top: 0,
      behavior: 'smooth'
    })
  }
}
function handleMapChange(data) {
  if (data.address) {
    drawerForm.address = data.address
  }
  drawerForm.lat = data.lat
  drawerForm.lng = data.lng
}

function addOwner() {
  drawerForm.owners.push({ name: '', phone: '', idCard: '', idCardAddress: '' })
}
function removeOwner(idx) {
  if (drawerForm.owners.length > 1) drawerForm.owners.splice(idx, 1)
}

const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/pms/house/importData")
const headers = ref({ Authorization: "Bearer " + getToken() })

function handleImportSuccess(response, file, fileList) {
  console.log("response", response)
  if (response.code == 200) {
    proxy.$modal.msgSuccess('导入成功')
    // 清理文件列表
    proxy.$refs.uploadRef.clearFiles()
    importDialogVisible.value = false
    getList()
  } else {
    proxy.$modal.msgError(response.msg)
    // 上传失败也清理文件列表
    proxy.$refs.uploadRef.clearFiles()
  }
}

// 添加错误处理函数
function handleImportError(error, file, fileList) {
  console.error("上传错误:", error)
  proxy.$modal.msgError('上传失败，请重试')
  // 清理文件列表
  proxy.$refs.uploadRef.clearFiles()
}
function handleExceed(files, uploadFiles) {
  proxy.$refs.uploadRef.clearFiles()
  proxy.$refs.uploadRef.handleStart(files[0])
}

onMounted(() => {
  getCommunityOptions()
  listArea({ pageNum: 1, pageSize: 1000, status: 1 }).then(res => {
    // 使用与区域管理相同的数据处理逻辑
    const normalizedData = normalizeAreaTree(res?.rows || [])
    console.log("normalizedData", normalizedData)
    areaOptions.value = normalizedData
  })
  getList()
})
</script>
<style lang="scss">
.upload-demo-btn {
  width: 668px;
  padding: 40px 30px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;


  border-radius: 6px;
  cursor: pointer;
  transition: all .3s ease;
  
  &:hover {
    // border-color: #409eff;
    // background-color: #f0f9ff;
  }
  
  .el-icon--upload {
    color: #c0c4cc;
    margin-bottom: 16px;
  }
}

.upload-demo-btn-text {
  color: rgb(220 38 38);
  font-weight: 600;
}

.upload-demo-btn-text-desc {
  color: rgb(107 114 128);
  font-size: 14px;
  margin-top: 10px;
  text-align: center;

  span {
    color: rgb(51, 112, 255);
    cursor: pointer;
  }
}

/* 拖拽状态样式 */
.el-upload.is-drag {
  .upload-demo-btn {
    width: 668px;
    padding: 30px;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: #f2f3f5;

  }
}


.el-upload-dragger{
  padding: 0 !important;
}

.el-upload.is-drag.is-dragover {
  .upload-demo-btn {
    border-color: #67c23a;
    background-color: #f0f9ff;
    transform: scale(1.02);
  }
}
</style>
